package org.example.test02.window;

import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import org.example.test02.utils.AliChatUtil;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;

public class ToolsWindowStreamChat implements ToolWindowFactory {



    private static DefaultListModel<String> chatModel = new DefaultListModel<>();
    // 中间的内容展示框
    private static JList<String> chatList = new JList<>(chatModel);
    private static String userInput = "";

    @Override
    public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout());

        chatList.setCellRenderer(new ChatListCellRenderer());
        JScrollPane scrollPane = new JScrollPane(chatList);
        mainPanel.add(scrollPane, BorderLayout.CENTER);//将显示聊天区域的内容放到中间

        // 下方的输入面板
        JPanel panel = new JPanel(new BorderLayout());
        JTextField inputField = new JTextField();//输入框组件
        JButton sendButton = new JButton("发送");//发送按钮
        panel.add(inputField, BorderLayout.CENTER);
        panel.add(sendButton, BorderLayout.EAST);
        mainPanel.add(panel, BorderLayout.SOUTH);//将下方的输入框和发送放到整个窗口的下边


        java.util.List<Message> messages = new ArrayList<>();
        messages.add(AliChatUtil.createMessage(Role.SYSTEM, "You are a helpful assistant."));
        // 处理发送按钮点击事件
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                userInput = inputField.getText();
                //将用户输入的内容放到对话框
                if (!userInput.isEmpty()) {
                    //将信息追加到对话框scrollPane中
                    addContentToChatList(userInput, "user");
                    //同时清空输入框的内容
                    inputField.setText("");
                    //向阿里云流失请求
                    new AliStreamChatWorker(userInput).execute();
                }

            }
        });

        // 将主面板添加到 ToolWindow
        ContentFactory contentFactory = ContentFactory.getInstance();
        Content content = contentFactory.createContent(mainPanel, "", false);
        toolWindow.getContentManager().addContent(content);
    }

    private static class AliStreamChatWorker extends SwingWorker<Void, String> {
        private final String userInput;

        public AliStreamChatWorker(String userInput) {
            this.userInput = userInput;
        }

        @Override
        protected Void doInBackground() throws Exception {
            String API_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
            final String API_KEY = "sk-5bffade0f3fb46d49abf169956ca460e"; // 替换为你的 API Key
            String requestBody = """
            {
                "model": "qwen-plus",
                "messages": [
                    {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": "冒泡排序"}
                ],
                "stream": true
            }
            """;

            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(API_URL))
                    .header("Authorization", "Bearer " + API_KEY)
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .build();

            ObjectMapper mapper = new ObjectMapper();
            // 流式接收响应
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            String[] lines = response.body().split("\n");
            for (String line : lines) {
                if (line.startsWith("data:")) {
                    String json = line.substring(5).trim();
                    if (!json.equals("[DONE]")) {
                        JsonNode root = mapper.readTree(json);
                        String content = root
                                .path("choices")
                                .get(0)
                                .path("delta")
                                .path("content")
                                .asText();
                        publish(content);
                        System.out.println(content);
                    }
                }
            }
            return null;
        }

        @Override
        protected void process(List<String> chunks) {
            for (String content : chunks) {
                addContentToChatList(content, "assistant");
            }
        }
    }

    private static void addContentToChatList(String text, String role) {
        ApplicationManager.getApplication().invokeLater(() -> {
            if (role.equals("user")) {
                chatModel.addElement("用户: " + text);
            } else {
                chatModel.addElement("ChatRobot: " + text);
            }
            chatList.ensureIndexIsVisible(chatModel.size() - 1);
        });
    }

    private static class ChatListCellRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            String text = value.toString();
            if (text.startsWith("用户: ")) {
                setHorizontalAlignment(SwingConstants.RIGHT);
            } else {
                setHorizontalAlignment(SwingConstants.LEFT);
            }
            return c;
        }
    }


}
